const {
    json
} = require('body-parser');
const express = require('express');
const sqlQuery = require('./lostSql');
const add = require('./ip');

let app = express();

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

//获取用户列表
app.get('/api/userList', async (req, res) => {
    //请求的信息：req对象
    //响应的操作和信息：res对象
    let strSql = `
        select *
        from user
    `
    let userList = await sqlQuery(strSql);
    res.json({
        state: 'OK',
        userList
    })
})


//获取登录信息(是登录成功还是失败)
app.get('/login', async (req, res) => {
    //请求的信息：req对象
    //响应的操作和信息：res对象

    let strSql = `
        select *
        from user   
        where uemail = '${req.query.id}' and upw = '${req.query.pw}' 
    `
    let list = await sqlQuery(strSql);
    if (list.length == 0) {
        // console.log(req.query.id,'密码错误');
        res.json({
            state: 'ERROR'
        })
    } else {
        res.json({
            state: 'OK',
            id: req.query.id,
            userInfo: {
                email: list[0].uemail,
                name: list[0].uname
            }
        })
    }
})

/*
获取失物列表
id填邮箱，no填no值，为可选项：
    - 无id为所有列表
    - 有id为个人发布的列表
    - 有no为指定的项
*/
app.get('/lostList', async (req, res) => {
    let strSql;
    if (req.query.id != undefined) {
        strSql = `
            select *
            from lostList
            where authorEmail='${req.query.id}'
        `
    }else if(req.query.no != undefined){
        strSql = `
            select *
            from lostList
            where no='${req.query.no}'
        `
    }else{
        strSql = `
            select *
            from lostList
        `
    }

    let lostList = await sqlQuery(strSql);
    res.json({
        state: 'OK',
        lostList
    })
})

//获取失物列表最大no值
app.get('/listNumMax', async (req, res) => {
    let strSql = `
        select max(no) as max
        from lostList
    `
    let listNumMax = await sqlQuery(strSql);
    // console.log(listNumMax);
    res.json({
        state: 'OK',
        max: listNumMax[0].max
    })
})

//删除失物列表
app.get('/del', async (req, res) => {
    let strSql = `
        delete
        from lostList
        where no = '${req.query.no}'
    `
    let delList = await sqlQuery(strSql);
    if (delList.affectedRows == 0) {
        res.json({
            state: 'OK',
            result: false
        })
    } else {
        res.json({
            state: 'OK',
            result: true
        })
    }
})

//添加账号
app.get('/addUser', async (req, res) => {
    let strSql = `
        insert
        into user
        values('${req.query.email}','${req.query.name}','${req.query.pw}')
    `
    let strSql1 = `
        select *
        from user
    `
    let userList = await sqlQuery(strSql1);

    let mark = true;
    userList.forEach((item, index) => {
        if (item.uemail == req.query.email) {
            mark = false;
        }
    })
    if (mark) {
        await sqlQuery(strSql);
        res.json({
            state: 'OK',
            result: true
        })
    } else {
        res.json({
            state: 'OK',
            result: false
        })
    }
})

//更改密码和名字

//名字
app.get('/userChange/name', async (req, res) => {
    let userChangeSql = `
        update user
        set uname = '${req.query.name}'
        where uemail = '${req.query.email}'
    `
    let userChange = await sqlQuery(userChangeSql);
    res.json({
        state: 'OK',
    })
})
//密码
app.get('/userChange/pw', async (req, res) => {
    let userSql = `
        select *
        from user
        where uemail = '${req.query.email}'
    `
    let user = await sqlQuery(userSql);
    if (req.query.oldPw == user[0].upw) {
        let userChangeSql = `
            update user
            set upw = '${req.query.nowPw}'
            where uemail = '${req.query.email}'
        `
        await sqlQuery(userChangeSql);
        res.json({
            state: 'OK',
        })
    } else {
        res.json({
            state: 'ERROR'
        })
    }

})

// 更新失物列表信息
app.get('/update', async (req, res) => {
    let lostBefore = `
        select *
        from lostList
        where no = '${req.query.no}'
    `
    let lostBeforeList = await sqlQuery(lostBefore);
    let name = req.query.name ? req.query.name : lostBeforeList[0].lostName
    let description = req.query.des ? req.query.des : lostBeforeList[0].description
    let tel = req.query.tel ? req.query.tel : lostBeforeList[0].tel
    let LorF = req.query.LorF ? req.query.LorF : lostBeforeList[0].LorF
    // console.log(name);
    let strSql = `
        update lostList
        set lostName = '${name}',description = '${description}',tel = '${tel}',LorF = '${LorF}'
        where no = ${req.query.no}
    `
    let update = await sqlQuery(strSql);
    res.json({
        state: 'OK'
    })
})

//搜索
app.get('/search', async (req, res) => {
    let strSql = `
        select *
        from lostList
        where lostName like '%${req.query.word}%'
    `
    let search = await sqlQuery(strSql);
    res.json({
        state: 'OK',
        search
    })
})

//添加失物
app.get('/addLost', async (req, res) => {
    let strSql = `
        insert
        into lostList
        values ('${req.query.no}','${req.query.email}','${req.query.date}','${req.query.name}','${req.query.des}','${req.query.tel}','${req.query.LorF}')
    `
    let addLost = await sqlQuery(strSql);
    res.json({
        state: 'OK',
        addLost
    })
})

//获取lost列表事项
app.get('/lost',async (req, res)=>{
    let strSql = `
        select *
        from lostList
        where LorF = 'lost'
    `
    let lost = await sqlQuery(strSql);
    res.json({
        state: 'OK',
        lost
    })
})

//获取find列表事项
app.get('/find',async (req, res)=>{
    let strSql = `
        select *
        from lostList
        where LorF = 'find'
    `
    let find = await sqlQuery(strSql);
    res.json({
        state: 'OK',
        find
    })
})


//服务器启动
app.listen(3000, function () {
    console.log("服务器启动成功");
    console.log('内网：', 'http://127.0.0.1:3000');
    console.log('公网：', 'http://' + `${add}` + ':3000');
})